<?php
namespace plugins\encyclopedias\controller;

use cmf\controller\ApiPluginBaseController;
use GrabImage;
use plugins\encyclopedias\classes\AipImageClassify;
use plugins\encyclopedias\classes\lib\AipBase;
use think\Db;
use think\Request;
use RongCloud\RongCloud;

require 'RongCloud/RongCloud.php';

define("APPKEY", 'p5tvi9dspe834');
define('APPSECRET', 'b8fHKCCpFMNe0N');

/**
 * 
 */
class ApiIndexController extends ApiPluginBaseController
{
    private  $pageNum = "20";
    //百度 APPID AK SK
    const APP_ID = '23843813';
    const API_KEY = 'yvau6pLmIX1xZ7DGdRjuivZg';
    const SECRET_KEY = 'yI33gD5PGV1BoIGECvyfLskF2QVvGBIp';


    /**
     * 百科列表页面
     */
    public function getEncyList()
    {
        $data = $this->request->param();
        $where = 1;

        if(!empty($data['category'])){
            $where .= ' and category='.$data['category'];
        }
        if(!empty($data['title'])){
            $where .= " and title like '%" . $data['title'] . "%' ";
            //插入搜索历史
            if (!empty($data['userid'])) {
                $is_add = Db::name('encyclopedias_history')->where('title',$data['title'])->where('userid',$data['userid'])->count();
                if($is_add == 0){
                    $add_data['userid'] = $data['userid'];
                    $add_data['title'] = $data['title'];
                    $add_data['addtime'] = time();
                    Db::name('encyclopedias_history')->insert($add_data);
                }
            }
        }
        $sear['pagesize'] = isset( $data['pagesize'] ) ? $data [ 'pagesize' ] : $this->pageNum;
        $list = db('encyclopedias')->where($where)->paginate($sear['pagesize'] ,false,['page'=>$data['page']])->each(function ($item){
            $category = db('encyclopedias_category')->where('id',$item['category'])->find();
            if(!empty($category)){
                $item['category'] = $category['title'];
            }
            $item['time'] = date('Y-m-d H:i:s',$item['time']);
            $name = '-';
            if($item['userid'] == 0){
                $name = '管理员';
            }
            $item['username'] = $name;
            if(!empty($item['image'])){
                $item['image'] = ZY_APP_PATH.$item['image'];
            }
            $item['content'] = '';
            return $item;
        });
        return api_json_echo( true , '获取成功' , $list , 200);
    }

    /**
     * 发布
     */
    public function addEncy()
    {
        $param = $this->request->param();
        $add['userid'] = $param['userid'];
        $add['time'] = time();
        $add['title'] = $param['title'];
        $add['content'] = $param['content'];
        $add['image'] = $param['image'];
        $add['category'] = $param['category'];

        $return = db('encyclopedias')->insert($add);
        if ($return) {
            return api_json_echo(true, '添加成功！', null, 200);
        } else {
            return api_json_echo(false, '添加失败！', null, 101);
        }
    }

    /**
     * 百科详情
     */
    public function encyInfo()
    {
        $param = $this->request->param();
        $info = db('encyclopedias')->where('id',$param['id'])->find();
        if(!empty($info['image'])){
            $info['image'] = ZY_APP_PATH.$info['image'];
        }
        if(!empty($info['content'])){
            $info['content'] = htmlspecialchars_decode($info['content']);
        }
        //获取收藏状态
        $is_collection = false;
        if(!empty($param['userid'])){
            $count = db('encyclopedias_collection')->where('userid',$param['userid'])->where('cid',$param['id'])->count();
            if($count>0){
                $is_collection = true;
            }
        }
        $info['is_collection'] = $is_collection;

        db('encyclopedias')->where('id',$param['id'])->setInc('browse_number');
        return api_json_echo( true , '获取成功' , $info , 200);
    }

    /**
     * 百科分类列表
     */
    public function categoryList()
    {
        $data = $this->request->param();
        $where = 1;
        if(!empty($data['title'])){
            $where .= " and title like '%" . $data['title'] . "%' ";
        }
        $list = db('encyclopedias_category')->where($where)->order('sort')->select()->each(function ($item){
            if(!empty($item['imgurl'])){
                $item['imgurl'] = ZY_APP_PATH.$item['imgurl'];
            }
            return $item;
        });
        return api_json_echo( true , '获取成功' , $list , 200);
    }

    /**
     * 添加/取消收藏
     */
    public function subCollection()
    {
        $param = $this->request->param();
        if(empty($param['userid'])){
            return api_json_echo(false, '未获取到userid！', null, 101);
        }
        if(empty($param['id'])){
            return api_json_echo(false, '未获取到百科id！', null, 101);
        }
        $userid = $param['userid'];
        $id = $param['id'];

        $info = db('encyclopedias')->where('id',$id)->find();
        if(empty($info)){
            return api_json_echo(false, '该百科不存在！', null, 101);
        }
        //判断该用户是否收藏
        $count = db('encyclopedias_collection')->where('cid',$id)->where('userid',$userid)->count();
        if($count>0){
            $return = db('encyclopedias_collection')->where('cid',$id)->where('userid',$userid)->delete();
        }else{
            $add['addtime'] = time();
            $add['cid'] = $id;
            $add['userid'] = $userid;
            $return = db('encyclopedias_collection')->insert($add);
        }
        if ($return) {
            return api_json_echo(true, '操作成功！', null, 200);
        } else {
            return api_json_echo(false, '操作失败！', null, 101);
        }
    }

    /**
     * 批量取消收藏
     */
    public function deleteCollection()
    {
        $param = $this->request->param();
        if(empty($param['id'])){
            return api_json_echo(false, '未获取到id！', null, 101);
        }
        $id = $param['id'];

        $return = db('encyclopedias_collection')->whereIn('id',$id)->delete();
        return api_json_echo(true, '操作成功！', '操作成功', 200);
    }


    /**
     * 商品收藏列表
     */
    public function goodsCollectList()
    {
        $param = $this->request->param();
        if(empty($param['userid'])){
            return api_json_echo(false, '未获取到userid！', null, 101);
        }
        $collect = db('goods_collect')->where('uid', $param['userid'])->find();
        $gids = [];
        if (!empty($collect)) {
            $gids = preg_split('/[\,+]/u', $collect['goods_id'], null, PREG_SPLIT_NO_EMPTY); //拆分字符串
        }
        $list = db('goods')->where('id', 'in', $gids)->select()->each(function ($item){

            $item['goods_img'] = ZY_APP_PATH.$item['goods_img'];
            return $item;
        });
        return api_json_echo(true, '获取成功', $list, 200);
    }


    /**
     * 商品添加/取消 收藏
     */
    public function goodsCollectManage()
    {
        $param = $this->request->param();
        if(empty($param['userid'])){
            return api_json_echo(false, '未获取到userid！', null, 101);
        }
        if(empty($param['goods_id'])){
            return api_json_echo(false, '未获取到goods_id！', null, 101);
        }
        $collect = Db::name('goods_collect')->where('uid', $param['userid'])->find();
        switch ($param['type']) {
            case 1: //添加收藏
                if (!empty($collect)) {
                    $coll = $collect['goods_id'] . "," . $param['goods_id'] . ",";
                    $da   = [
                        'goods_id' => $coll,
                    ];
                    Db::name('goods_collect')->where('uid', $param['userid'])->update($da);
                } else {
                    $da = [
                        'uid'      => $param['userid'],
                        'goods_id' => "," . $param['goods_id'] . ",",
                    ];
                    Db::name('goods_collect')->insert($da);
                }
                break;
            case 2: //取消收藏
                $coll = str_replace(',' . $param['goods_id'] . ',', "", $collect['goods_id']);
                $da   = [
                    'goods_id' => $coll,
                ];
                Db::name('goods_collect')->where('uid', $param['userid'])->update($da);
                break;
            default:
                # code...
                break;
        }
        return api_json_echo(true, '操作成功', null, 200);
    }

    /**
     * 收藏列表
     */
    public function collectionList()
    {
        $param = $this->request->param();
        if(empty($param['userid'])){
            return api_json_echo(false, '未获取到userid！', null, 101);
        }
        $list = db('encyclopedias_collection')->where('userid',$param['userid'])->select()->each(function ($item){
            $info = db('encyclopedias')->where('id',$item['cid'])->find();
            if(!empty($info['image'])){
                $info['image'] = ZY_APP_PATH.$info['image'];
            }
            if(!empty($info['content'])){
                $info['content'] = htmlspecialchars_decode($info['content']);
            }
            $item['info'] = $info;

            $item['addtime'] = date('Y-m-d H:i:s',$item['addtime']);
            return $item;
        });
        return api_json_echo( true , '获取成功' , $list , 200);
    }

    /**
     * 上传图片
     */
    public function uploadImage($file)
    {
        $upload_path = "/upload/images";
        $res = uploadImg($file, $upload_path);
        if ($res['status'] != true) {
            return api_json_echo(false, '上传失败', $res['message'], $res['code']);
        }
        return $res['data'];
    }


    /*
     * 保存图片
     * @param $url 要保存的链接
     * @return 保存的字节数，失败则返回 false
     */
    function change_url_image($img_url)
    {
        $object = new GrabImage();
        $base_dir = "upload/images"; // 本地保存的路径
        $img_path =  $object->getInstances($img_url , $base_dir);
        return $img_path;
    }

    /**
     * 百度花草识别
     */
    public function distinguish(){
        $param = $this->request->param();
//        $file = $_FILES['file'];
//        $up_res = $this->uploadImage($file);

        $client = new AipImageClassify(self::APP_ID, self::API_KEY, self::SECRET_KEY);
//        $url = file_get_contents(ZY_APP_PATH.$up_res);
        // 如果有可选参数
        $options = array();
        $options["baike_num"] = 3;

        // 带参数调用植物识别
        $res = $client->plantDetect($param['image'], $options);

        if(empty($res['result'])){
            return api_json_echo(true, '未识别成功！', null, 200);
        }
        if(empty($res['result'][0])){
            return api_json_echo(true, '未获取到结果！', null, 200);
        }
        $result = $res['result'][0];
        if($result['name']=='非植物'){
            $result['baike_info'] = null;
        }
        if(empty($result['baike_info'])){
            $result['baike_info'] = null;
        }
        //查询数据库有无数据
        $info = db('encyclopedias')->where('title',$result['name'])->find();
        if(empty($info) || empty($info['content'])){
            //加入数据库
            //1.下载图片
            $image_path = $this->change_url_image($result['baike_info']['image_url']);

            $add['userid'] = 0;
            $add['time'] = time();
            $add['title'] = $result['name'];
            $add['image'] = '/'.$image_path;
            $add['category'] = 1;
            $add['content'] = $result['baike_info']['description'];
            db('encyclopedias')->insert($add);
        }

        $info = db('encyclopedias')->where('title',$result['name'])->find();
        $result['baike_info']['baike_url'] = ZY_APP_PATH.'/flower_content.html?id='.$info['id'];

        return api_json_echo( true , '获取成功' , $result , 200);
    }

    /**
     * 百度花草识别
     */
    public function distinguishForFile(){
        $param = $this->request->param();
        $file = $_FILES['file'];
        $up_res = $this->uploadImage($file);

        $client = new AipImageClassify(self::APP_ID, self::API_KEY, self::SECRET_KEY);
        $file_path = explode("plugins",__FILE__);
        $file_local_path = $file_path[0].$up_res;
        $url = base64_encode(file_get_contents($file_local_path));
        // 如果有可选参数
        $options = array();
        $options["baike_num"] = 3;

        // 带参数调用植物识别
        $res = $client->plantDetect( $url, $options);

        if(empty($res['result'])){
            return api_json_echo(true, '未识别成功！', null, 200);
        }
        if(empty($res['result'][0])){
            return api_json_echo(true, '未获取到结果！', null, 200);
        }
        $result = $res['result'][0];
        if($result['name']=='非植物'){
            $result['baike_info'] = null;
        }
        if(empty($result['baike_info'])){
            $result['baike_info'] = null;
        }

        //查询数据库有无数据
        $info = db('encyclopedias')->where('title',$result['name'])->find();
        if(empty($info) || empty($info['content'])){
            //加入数据库
            //1.下载图片
            $image_path = $this->change_url_image($result['baike_info']['image_url']);

            $add['userid'] = 0;
            $add['time'] = time();
            $add['title'] = $result['name'];
            $add['image'] = '/'.$image_path;
            $add['category'] = 1;
            $add['content'] = $result['baike_info']['description'];
            db('encyclopedias')->insert($add);


        }
        $info = db('encyclopedias')->where('title',$result['name'])->find();
        $result['baike_info']['baike_url'] = ZY_APP_PATH.'/flower_content.html?id='.$info['id'];
        return api_json_echo( true , '获取成功' , $result , 200);
    }

    /**
     * 添加好友
     */
    public function addFriends(){
        $param = $this->request->param();
        if(empty($param['userid'])){
            return api_json_echo(false, '未获取到userid！', null, 101);
        }
        if(empty($param['friendid'])){
            return api_json_echo(false, '未获取到friendid！', null, 101);
        }
        if($param['userid'] == $param['friendid']){
            return api_json_echo( true , '无法添加自己为好友' , '无法添加自己为好友' , 200);
        }
        $friend_info = db('friend')->where('userid',$param['userid'])->where('friendid',$param['friendid'])->find();
        if(!empty($friend_info)){
            if($friend_info['status'] == 1){
                return api_json_echo( true , '对方已是好友' , '对方已是好友' , 200);
            }elseif ($friend_info['status'] == 2){
                $res = db('friend')->where('id',$friend_info['id'])->update(['status'=>0]);
                if($res){
                    return api_json_echo( true , '添加成功' , '添加成功' , 200);
                }
                return api_json_echo( false , '添加失败' , '添加失败' , 300);
            }elseif ($friend_info['status'] == 0){
                return api_json_echo( true , '等待对方审核通过' , '等待对方审核通过' , 200);
            }
        }
        $add_data['userid'] = $param['userid'];
        $add_data['friendid'] = $param['friendid'];
        $add_data['add_time'] = time();
        $res = db('friend')->insert($add_data);
        if($res){
            return api_json_echo( true , '添加成功' , '添加成功' , 200);
        }
        return api_json_echo( false , '添加失败' , '添加失败' , 300);
    }

    /**
     * 好友审核列表
     */
    public function friendsCheckList(){
        $param = $this->request->param();
        if(empty($param['userid'])){
            return api_json_echo(false, '未获取到userid！', null, 101);
        }
        $list = db('friend')->where('status',0)->where('friendid',$param['userid'])->select()->each(function ($item){
            $info = db('member')->where('uid',$item['userid'])->find();
            if(!empty($info)){
                if(!empty($info['head_portrait'])){
                    $info['head_portrait'] = ZY_APP_PATH.$info['head_portrait'];
                }
            }
            $item['info'] = $info;
            return $item;
        });
        return api_json_echo( true , '获取成功' , $list , 200);
    }

    /**
     * 好友审核操作
     */
    public function friendsCheck(){
        $param = $this->request->param();
        if(empty($param['id'])){
            return api_json_echo(false, '未获取到id！', null, 101);
        }
        if(empty($param['status'])){
            return api_json_echo(false, '未获取到操作状态status！', null, 101);
        }
        $res = db('friend')->where('id',$param['id'])->update(['status'=>$param['status']]);
        if($res){
            if($param['status'] == 1){
                $infos = db('friend')->where('id',$param['id'])->find();

                $add_data['userid'] = $infos['friendid'];
                $add_data['friendid'] = $infos['userid'];
                $add_data['add_time'] = time();
                $add_data['status'] = 1;
                db('friend')->insert($add_data);
            }
            return api_json_echo( true , '操作成功' , '操作成功' , 200);
        }
        return api_json_echo( false , '操作失败' , '操作失败' , 300);
    }

    /**
     * 好友列表
     */
    public function friendsList(){
        $param = $this->request->param();
        if(empty($param['userid'])){
            return api_json_echo(false, '未获取到userid！', null, 101);
        }
        $list = db('friend')->where('status',1)->where('userid',$param['userid'])->select()->each(function ($item){
            $info = db('member')->where('uid',$item['friendid'])->find();
            if(!empty($info)){
                if(!empty($info['head_portrait'])){
                    $info['head_portrait'] = ZY_APP_PATH.$info['head_portrait'];
                }
            }
            $item['info'] = $info;
            return $item;
        });
        return api_json_echo( true , '获取成功' , $list , 200);
    }

    /**
     * 添加好友黑名单
     */
    public function addFriendBlack(){

        $param = $this->request->param();
        if(empty($param['userid'])){
            return api_json_echo(false, '未获取到userid！', null, 101);
        }
        if(empty($param['friendid'])){
            return api_json_echo(false, '未获取到friendid！', null, 101);
        }
        $is_add = db('friend_blacklist')->where('userid',$param['userid'])->where('beuserid',$param['friendid'])->count();
        if($is_add>0){
            return api_json_echo( true , '该好友已在黑名单' , '该好友已在黑名单' , 200);
        }

        $add_data['userid'] = $param['userid'];
        $add_data['beuserid'] = $param['friendid'];
        $add_data['createtime'] = time();
        $res = db('friend_blacklist')->insert($add_data);
        if($res){
            db('friend')->where('userid',$param['userid'])->where('friendid',$param['friendid'])->update(['status'=>3]);

            $blacklist = [];
            array_push($blacklist,$param['friendid']);

            $RongSDK = new RongCloud(APPKEY, APPSECRET);
            $user = [
                'id' =>$param['userid'],//用户 Id。
                'blacklist' => $blacklist,//被加入黑名单的用户 Id，每次最多添加 20 个用户。
            ];
            $black = $RongSDK->getUser()->Blacklist();
            $black->add($user);

            return api_json_echo( true , '添加成功' , '添加成功' , 200);
        }
        return api_json_echo( false , '添加失败' , '添加失败' , 300);
    }

    /**
     * 移除好友黑名单
     */
    public function removeFriendBlack(){

        $param = $this->request->param();
        if(empty($param['userid'])){
            return api_json_echo(false, '未获取到userid！', null, 101);
        }
        if(empty($param['friendid'])){
            return api_json_echo(false, '未获取到friendid！', null, 101);
        }

        $info =  db('friend_blacklist')->where('userid',$param['userid'])->where('beuserid',$param['friendid'])->find();
        if(!empty($info)){
            db('friend')->where('userid',$info['userid'])->where('friendid',$info['beuserid'])->update(['status'=>1]);

            db('friend_blacklist')->where('id',$info['id'])->delete();

            $blacklist = [];
            array_push($blacklist,$info['beuserid']);

            $RongSDK = new RongCloud(APPKEY, APPSECRET);
            $user = [
                'id' =>$info['userid'],//用户 Id。
                'blacklist' => $blacklist,//被加入黑名单的用户 Id，每次最多添加 20 个用户。
            ];
            $black = $RongSDK->getUser()->Blacklist();
            $res = $black->remove($user);

            return api_json_echo( true , '操作成功' , '操作成功' , 200);
        }
        return api_json_echo( false , '操作失败' , '操作失败' , 300);
    }

    /**
     * 黑名单列表
     */
    public function friendsBlackList(){
        $param = $this->request->param();
        if(empty($param['userid'])){
            return api_json_echo(false, '未获取到userid！', null, 101);
        }
        $list = db('friend_blacklist')->where('userid',$param['userid'])->select()->each(function ($item){
            $info = db('member')->where('uid',$item['beuserid'])->find();
            if(!empty($info)){
                if(!empty($info['head_portrait'])){
                    $info['head_portrait'] = ZY_APP_PATH.$info['head_portrait'];
                }
            }
            $item['info'] = $info;
            return $item;
        });
        return api_json_echo( true , '获取成功' , $list , 200);
    }

    /**
     * 删除好友
     */
    public function delFriend(){
        $param = $this->request->param();
        if(empty($param['userid'])){
            return api_json_echo(false, '未获取到userid！', null, 101);
        }
        if(empty($param['friendid'])){
            return api_json_echo(false, '未获取到friendid！', null, 101);
        }
        $friend_info = db('friend')->where('userid',$param['userid'])->where('friendid',$param['friendid'])->find();
        if(empty($friend_info)){
            return api_json_echo( true , '该好友不存在' , '' , 200);
        }
        $res = db('friend')->where('id',$friend_info['id'])->delete();
        if($res){
            db('friend')->where('friendid',$param['userid'])->where('userid',$param['friendid'])->find();
            return api_json_echo( true , '删除成功' , '删除成功' , 200);
        }
        return api_json_echo( false , '删除失败' , '删除失败' , 300);
    }

    /**
     * 获取用户商品搜索记录,分类
     */
    public function getUserHistory(){
        $param = $this->request->param();
        if(empty($param['userid'])){
            return api_json_echo(false, '未获取到userid！', null, 101);
        }
        $hot_list = Db::name('encyclopedias')->where('islock',0)->limit(5)->select();
        $hot = [];
        foreach ($hot_list as $item){
            array_push($hot,$item['title']);
        }
        //获取用户搜索历史
        $history = Db::name('encyclopedias_history')->where('userid',$param['userid'])->select();

        $res = [
            'hot'=>$hot,
            'history'=>$history
        ];
        return api_json_echo( true , '获取成功' , $res , 200);
    }


}